<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>最家-登录</title>
  <link rel="stylesheet" type="text/css" href="css/public.css" />
  <link rel="stylesheet" type="text/css" href="css/login.css" />
</head>

<body>
  <!-------------------login-------------------------->
  <div class="login">
    <form action="#" method="post">
      <h1><a href="index.html"><img src="img/temp/logo.png"></a></h1><br>
      <div class="msg-warn hide"><b>公共场所不建议自动登录，以防账号丢失</b></div>
      <p>
        <h2>用户登录</h2>
      </p>
      <p><input type="text" name="" value="" placeholder="昵称/邮箱/手机号"></p>
      <p><input type="password" name="" value="" placeholder="密码"></p>
      <p><input type="button" name="" value="登  录"></p>
      <p class="txt">
        <a class="" href="reg.html">免费注册</a>
        <a href="javascript:;">忘记密码？</a>
      </p>
    </form>
  </div>
</body>
<script>
  //1 获取页面中的节点
  let inputObj = document.querySelectorAll('input');
  //2 给登录绑定事件 DOM二级
  inputObj[2].addEventListener('click', ajaxFn);

  function ajaxFn() {
    //3 获取表单数据
    let name = inputObj[0].value;
    let pwd = inputObj[1].value;
    //4 调用ajax发送数据
    let xhr = new XMLHttpRequest();
    xhr.open('post', './data/login.php');
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    let data = `user=${name}&pwd=${pwd}`;
    xhr.send(data);
    console.log(data);
    //5 接收结果进行提示
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4 && xhr.status == 200) {
        let str = xhr.responseText;
        str = JSON.parse(str);
        console.log(str);
        // 6 根据返回的结果进行提示
        if (str.code == 200) {
          alert("登录成功,点击返回首页");
          window.location.href = 'index.html';
        }
        if (str.code == 500) alert("登录失败，用户名或密码输入错误，请重新尝试！");
      }
    }
  }
</script>

</html>